package com.zhi.blog.aspect;



import com.zhi.blog.domain.common.BaseRequest;
import com.zhi.common.exception.base.BaseException;
import org.apache.commons.collections4.CollectionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * 静态校验切面
 * @author ftz-lover
 * @version 1.0
 * @date 2023/12/17 16:21
 */
@Aspect
@Component
@Order(1)
public class StaticValidate {

    private static final Validator defaultValidator = Validation.buildDefaultValidatorFactory().getValidator();

    @Around("execution(public * com.zhi.blog.service.impl..*(..))")
    public Object doThriftPointCut(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        Object obj;
            // 参数校验
            validate(args);
            obj = joinPoint.proceed();
            return obj;
    }
    private void validate(Object[] args) throws Throwable {
        Object request = null;
        for (Object param : args) {
            if (param instanceof BaseRequest) {
                request = param;
                break;
            }
        }
        if (request == null) {
            return;
        }
        // 静态校验
        Set<ConstraintViolation<Object>> validateResult = defaultValidator.validate(request);
        if (CollectionUtils.isNotEmpty(validateResult)) {
            throw new BaseException(validateResult.iterator().next().getMessage());
        }
        // 个性化校验
        ((BaseRequest)request).validate();
    }
}

